package com.xzy.rabbit.demo.exchange.a;

import com.rabbitmq.client.Connection;
import com.xzy.rabbit.common.util.RabbitUtil;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * Fanout交换机（发布订阅模式）
 *
 * @author xzy
 * @date 2021/9/2710:39
 */
class Main {
    private static final String EXCHANGE_NAME = "xzy.exchange.fanout";
    private static final Integer MESSAGE_COUNT = 100;
    private static final long WORK_TIME = 3000L;

    private static final String QUEUE_NAME_1 = "xzy.queue.fanout1";
    private static final String QUEUE_NAME_2 = "xzy.queue.fanout2";
    private static final String ROUTING_KEY_1 = "key1";
    private static final String ROUTING_KEY_2 = "key2";
    private static final String ROUTING_KEY_3 = "key3";

    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        // 1.获取连接
        Connection connection = RabbitUtil.getConnection();

        // 2.发布消息
        Thread producer = new Thread(new Producer(connection, EXCHANGE_NAME, ROUTING_KEY_1, MESSAGE_COUNT, WORK_TIME), "PRODUCER");
        producer.start();

        // 2.消费消息
        Thread consumer1 = new Thread(new Consumer(connection, EXCHANGE_NAME, QUEUE_NAME_1, ROUTING_KEY_2), "CONSUMER1");
        Thread consumer2 = new Thread(new Consumer(connection, EXCHANGE_NAME, QUEUE_NAME_2, ROUTING_KEY_3), "CONSUMER2");
        consumer1.start();
        consumer2.start();

        producer.join();
        consumer1.join();
        consumer2.join();

        /**
         * 注意：虽然发送消息和接收消息时指定的ROUTING_KEY不同，但是两个队列依然能够接收到消息
         * 原因：声明的交换机是FANOUT交换机（将接收到的所有消息分发给与之绑定的所有队列，无视ROUTING_KEY）
         * @see Producer
         */
    }
}
